<?php

if (!empty($_FILES))
{
    //Get File extension
    $fileExt = substr($_FILES['Filedata']['name'], -4);
    $fileName = md5($_FILES['Filedata']['name']);
    $tempFile = $_FILES['Filedata']['tmp_name'];
    $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . date('Y-m-d') . '/';
    $targetFile =  str_replace('//','/',$targetPath) . $fileName . $fileExt;

    if (!is_dir($targetPath))
    {
        mkdir(str_replace('//', '/', $targetPath), 0755, true);
    }

    move_uploaded_file($tempFile, $targetFile);
    
    //If file is swf
    if(strtolower(substr($targetFile, -3)) == "swf")
    {
        //Get size
        $size = getimagesize($targetFile);
        
        //Set response
        $response = array(
            'src'   =>  str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetPath.$fileName.$fileExt),
            'width'     =>  $size[0],
            'height'    =>  $size[1]
        );
        
        echo json_encode($response);
        exit();
    }

    $imgsize = getimagesize($targetFile);
    switch(strtolower(substr($targetFile, -3)))
    {
        case "jpg":
            $image = imagecreatefromjpeg($targetFile);
            break;
        case "png":
            $image = imagecreatefrompng($targetFile);
            break;
        case "gif":
            $image = imagecreatefromgif($targetFile);
            break;
        default:
            exit;
            break;
    }

    $width = 200; //New width of image
    $height = $imgsize[1]/$imgsize[0]*$width; //This maintains proportions

    $src_w = $imgsize[0];
    $src_h = $imgsize[1];

    $picture = imagecreatetruecolor($width, $height);
    imagealphablending($picture, false);
    imagesavealpha($picture, true);
    $bool = imagecopyresampled($picture, $image, 0, 0, 0, 0, $width, $height, $src_w, $src_h);

    if($bool)
    {
        switch(strtolower(substr($targetFile, -3)))
        {
            case "jpg":
                imagejpeg($picture,$targetPath.$fileName."_thumb".$fileExt);
                break;
            case "png":
                imagepng($picture,$targetPath.$fileName."_thumb".$fileExt);
                break;
            case "gif":
                imagegif($picture,$targetPath.$fileName."_thumb".$fileExt);
                break;
        }
    }

    imagedestroy($picture);
    imagedestroy($image);

    //Set response
    $response = array(
        'src'       =>  str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetPath.$fileName."_thumb".$fileExt),
        'width'     =>  $width,
        'height'    =>  $height
    );
    
    //Response data
    echo json_encode($response);
    exit();
}
?>